public class BinarySearchTree {
    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        TreeNode node = new TreeNode(key);
        if (root == null) {
            root = node;
            return true;
        }

        TreeNode cur = root;
        TreeNode pre = null;
        while (cur != null) {
            pre = cur;
            if (cur.key == key) {
                return false;
            } else if (cur.key < key) {
                cur = cur.right;
            } else {
                cur = cur.left;
            }
        }

        if (pre.key < key) {
            pre.right = node;
        } else {
            pre.left = node;
        }
        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
        TreeNode cur = root;
        while (cur != null) {
            if (cur.key == key) {
                return cur;
            } else if (cur.key > key) {
                cur = cur.left;
            } else {
                cur = cur.right;
            }
        }
        return null;
    }

    //删除key的值
    public boolean remove(int key) {
        TreeNode pre = null;
        TreeNode cur = root;

        while (cur != null) {
            if (cur.key == key) {
                removeNode(pre,cur);
                return true;
            } else if (cur.key > key) {
                pre = cur;
                cur = cur.left;
            } else {
                pre = cur;
                cur = cur.right;
            }
        }
        return false;
    }

    /**
     *
     * @param pre
     * @param cur
     */
    public void removeNode(TreeNode pre, TreeNode cur) {
        if (cur.left == null) {
            if (cur == root) {
                root = cur.right;
            } else if (cur == pre.left) {
                pre.left = cur.right;
            } else {
                pre.right = cur.right;
            }
        } else if (cur.right == null) {
            if (cur == root) {
                root = cur.left;
            } else if (pre.left == cur) {
                pre.left = cur.left;
            } else {
                pre.right = cur.left;
            }
        } else {
            TreeNode tagPre = cur;
            TreeNode tag = cur.left;
            while (tag.right != null) {
                tagPre = tag;
                tag = tag.right;
            }
            cur.key = tag.key;
            if (tagPre.left == tag) {
                tagPre.left = tag.left;
            } else {
                tagPre.right = tag.left;
            }
        }
    }
}